//
//  FMDBHelpers.m
//  suRead
//
//  Created by 李 诗洋 on 16/1/4.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "FMDBHelpers.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

@interface FMDBHelpers()
@property (nonatomic,strong)FMDatabaseQueue *dataBaseQueue;
@end

@implementation FMDBHelpers

+ (instancetype)sharedInstance
{
    static FMDBHelpers *FMDBDelegateService;
    static dispatch_once_t devicedelegatehelperonce;
    dispatch_once(&devicedelegatehelperonce, ^{
        FMDBDelegateService = [FMDBHelpers new];
    });
    return FMDBDelegateService;
}
/**
 *  @brief  创建关于赞的表
 */
- (void)createZanTable
{
    NSString * doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:doc isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:doc withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir) {
            NSLog(@"Create Database Directory Failed.");
        }
        //NSLog(@"%@", documentsDirectory);
    }
    NSString * path = [doc stringByAppendingPathComponent:@"user.sqlite"];
    if (self.dataBaseQueue) {
        [self.dataBaseQueue close];
        self.dataBaseQueue = nil;
    }
    
    self.dataBaseQueue = [FMDatabaseQueue databaseQueueWithPath:path];
    
    NSString * sql = @"CREATE TABLE IF NOT EXISTS 'userZan' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'docid' VARCHAR(30), 'type' INTEGER)";
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        BOOL result =  [db executeUpdate:sql];
        //NSLog(@"creare %@",result?@"success":@"fail");
    }];
}
/**
 *  @brief 插入数据
 *
 *  @param docid_ 点赞对象的id
 *  @param type_  0:新闻点赞 1:报料点赞 2:评论点赞 3:问吧专家点赞 4:问吧问题评论点赞
 */
- (void)insertData:(NSString *)docid_ andType:(NSInteger)type_
{
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"INSERT INTO userZan (docid, type) VALUES (?,?)",docid_,  @(type_)];
    }];
}
/**
 *  @brief 查询是否点过赞
 *
 *  @param docid_ 点赞对象的id
 *
 *  @return 是否点过赞
 */
- (BOOL)queryData:(NSString *)docid_
             type:(NSInteger)type_
{
    __block BOOL isZan = NO;
    
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs = [db executeQuery:@"SELECT * FROM userZan WHERE docid=? and type=? ",docid_,@(type_)];
        
        while ([rs next]) {
            [rs close];
            isZan = YES;
        }
        [rs close];
    }];
    return isZan;
}

- (void)deleteData:(NSString *)docid_ type:(NSInteger)type_ {
    [self.dataBaseQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"DELETE FROM userZan WHERE docid=? and type=? ",docid_,@(type_)];
    }];
}
@end
